package com.cbg.sys.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.cbg.base.constant.Constant;
import com.cbg.base.utils.SpringContextHolder;
import com.cbg.sys.entity.*;
import com.cbg.sys.mapper.LineIniMapper;
import org.springframework.data.redis.core.RedisTemplate;
import java.time.LocalDate;
import java.time.Period;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <pre></pre>
 * <small> 2018-12-13 | chenbing </small>
 */
public class LineUtils {
    /**
     * 通过某天的排班配置生成当天的排班，排班配置可能是多个
     */
     public static List<Line> createLinesByInis(List<LineIni> inis,LocalDate date){
        List<Line> lines=new ArrayList<>();
        inis.forEach(x->{
            DateTime start = DateUtil.parse(x.getHeadTime(), Constant.FORMAT);
            DateTime end = DateUtil.parse(x.getTailTime(), Constant.FORMAT);
            DateTime go_tail;
            while ((go_tail = DateUtil.offset(start, DateField.of(x.getUnit()), x.getNum())).isBeforeOrEquals(end)) {
                lines.add(new Line().setRouteId(x.getRouteId()).setGoTimeHead(start.toString(Constant.FORMAT))
                        .setGoTimeTail(go_tail.toString(Constant.FORMAT)).setDateIn(date)
                        .setDateSign(Period.between(LocalDate.now(), date).getDays()));
                start = go_tail;
            }
            if(x.getType()==2)
                SpringContextHolder.getBean(LineIniMapper.class).updateById(x.setIsDone(true));
        });
        return lines;
    }

    /**
     * 3天的班次缓存
     */
    public static void putLinesIn3DaysToRedis(Map<String, Map<Integer, List<Line>>> lines) {
        RedisTemplate<String,Line> lineRedisTemplate= SpringContextHolder.getBean("lineRedisTemplate");
        lines.keySet().forEach(s->lines.get(s).keySet().forEach(
                x->{
                    lineRedisTemplate.opsForList().leftPushAll(Constant.LINE_SUFFIX+s+":"+x,lines.get(s).get(x));
                    lineRedisTemplate.expire(Constant.LINE_SUFFIX+s+":"+x,24, TimeUnit.HOURS);
                }));
    }
}
